package model

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"konglu-pay/constants"
	"strings"
	"time"
)

type JSONTime struct {
	time.Time
}

func (j JSONTime) UnmarshalJSON(data []byte) error {
	dataStr := strings.Replace(string(data), "\"", "", -1)
	// 自定义时间解析格式
	t, err := time.ParseInLocation(constants.TimeFormatFull, dataStr, time.Local)
	if err != nil {
		return err
	}
	j.Time = t
	return nil
}
func (j JSONTime) MarshalJSON() ([]byte, error) {
	b := make([]byte, 0, len(constants.TimeFormatFull)+2)
	b = append(b, '"')
	b = j.AppendFormat(b, constants.TimeFormatFull)
	b = append(b, '"')
	return b, nil
}

func (t JSONTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if t.Time.UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return t.Time, nil
}

func (t *JSONTime) Scan(v any) error {
	value, ok := v.(time.Time)
	if ok {
		*t = JSONTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to timestamp", v)
}

type BitBool bool

func (b BitBool) Value() (driver.Value, error) {
	if b {
		return []byte{1}, nil
	} else {
		return []byte{0}, nil
	}
}

func (b *BitBool) Scan(src any) error {
	v, ok := src.([]byte)
	if !ok {
		return errors.New("bad []byte type assertion")
	}
	*b = v[0] == 1
	return nil
}

type BaseDO struct {
	Id         string   `json:"id" gorm:"type:bigint(20);primary_key"`
	CreateTime JSONTime `json:"create_time,omitempty"`
	UpdateTime JSONTime `json:"update_time,omitempty"`
}
